package fy.input.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;

import fy.config.FyConfig;
import fy.util.DBUtil;
import fy.util.MyUtil;


public class BudgetCostCountDao {
	private static org.apache.commons.logging.Log log = LogFactory
			.getLog(BudgetCostNumberDao.class);

	private String number;

	private static final String QUERY_COST_COUNT_BY_NUMBER = "select v.budget_number, sum(v.count_cost),to_char(sysdate, 'yyyy-mm-dd hh:mi:ss') from budget_cost_count_view v where v.budget_number = ? group by v.budget_number";
	private static final String ERROR = "{success : false , msg : '查询已审批的费用合计失败，请重试或者联系OA系统管理员。'}";

	public void setNumber(String number) {
		this.number = number;
	}

	public String queryCost() {

		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		String result = null;
		try {
			conn = fy.util.DBUtil.connect(FyConfig.getOA_DB_CONFIG());

			pst = conn.prepareStatement(QUERY_COST_COUNT_BY_NUMBER);

			pst.setString(1, number);

			rs = pst.executeQuery();

			JSONObject jo = new JSONObject();
			if (rs.next()) {
				JSONObject data = new JSONObject();
				data.put("number", rs.getString(1));
				data.put("cost", rs.getString(2));
				data.put("time", rs.getString(3));
				jo.put("data", data);
			} else {
				JSONObject data = new JSONObject();
				data.put("number", number);
				data.put("cost", 0);
				data.put("time", MyUtil.getNowStr());
				jo.put("data", data);
			}
			jo.put("success", true);
			result = jo.toString();
		} catch (Exception e) {
			DBUtil.rollback(conn);
			e.printStackTrace();
			log.error("预算金额合计查询失败", e);
			result = ERROR;
		} finally {
			DBUtil.setAutoCommit(conn, true);
			DBUtil.close(rs, pst, conn);
		}
		return result;
	}

}
